﻿
namespace CodeBetter.Extensions
{
   using System.Collections.Generic;
   using System.IO;
using System;

   public static class StreamExtensions
   {
      /// <summary>
      /// Reads a stream line by line
      /// </summary>            
      /// <returns>The read lines</returns>
      public static List<string> ReadLines(this Stream stream)
      {
         var lines = new List<string>();
         using (var sr = new StreamReader(stream))
         {
            while (sr.Peek() >= 0)
            {
               lines.Add(sr.ReadLine());
            }
         }
         return lines;
      }
      
      /// <summary>
      /// Enumerate a stream over all lines in it
      /// </summary>
      /// <param name="stream"></param>
      /// <returns></returns>
      public static IEnumerable<string> StreamLines(this Stream stream)
      {
        // File.OpenText returns as StreamReader
        // actually you need a constructor of a stream
        using (var sr = new StreamReader(stream))
        {
          while (true)
          {
            string line = sr.ReadLine();
            if (line == null)
              yield break;
            yield return line;
          }
        }
      }

      public static IEnumerable<string> StreamLines(Func<Stream> streamConstructor)
      {
        using (Stream stream = streamConstructor()) {
          using (var sr = new StreamReader(stream))
          {
            while (true)
            {
              string line = sr.ReadLine();
              if (line == null)
                yield break;
              yield return line;
            }
          }
        }
      }

      /// <summary>
      /// Reads a complete stream
      /// </summary>            
      /// <returns>The contents of the stream</returns>
      public static string ReadAll(this Stream stream)
      {         
         using (var sr = new StreamReader(stream))
         {
            return sr.ReadToEnd();
         }         
      }
   }
}
